package xyz.quanguanjia.masterboy.adapter;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.util.HashMap;
import java.util.Map;

import xyz.quanguanjia.masterboy.MBDApplication;
import xyz.quanguanjia.masterboy.MBDGroupDetailModel;
import xyz.quanguanjia.masterboy.MBDHostManager;
import xyz.quanguanjia.masterboy.decoration.GroupDetailItemDecoration;
import xyz.quanguanjia.masterboy.util.MBDImageUtils;
import xyz.quanguanjia.masterboy.R;
import xyz.quanguanjia.masterboy.util.StringUtils;

public class GroupDetailAdapter extends RecyclerView.Adapter {
    private MBDGroupDetailModel groupDetail;

    private static final int VIEWTYPE_GROUP_DETAIL = 1;
    private static final int VIEWTYPE_GROUP_COMMENTS = 2;

    public GroupDetailAdapter(MBDGroupDetailModel gd) {
        this.groupDetail = gd;
    }

    public void setGroupDetail(MBDGroupDetailModel gd) {
        this.groupDetail = gd;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == VIEWTYPE_GROUP_DETAIL) {
            // 创建列表项视图
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_cell_group_detail, parent, false);
            return new MBDGroupDetailViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_cell_group_comments, parent, false);
            return new MBDGroupCommentsViewHolder(view);
        }

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        // 绑定数据到列表项视图
        int viewType = getItemViewType(position);
        if (viewType == VIEWTYPE_GROUP_DETAIL) {
            // 创建列表项视图
            ((MBDGroupDetailViewHolder) holder).bind(this.groupDetail);
        } else {
            MBDGroupCommentsModel model = this.groupDetail.getGroupComments().get(position - 1);
            ((MBDGroupCommentsViewHolder) holder).bind(model, position);
        }
    }

    @Override
    public int getItemCount() {
        if (this.groupDetail == null) {
            return 0;
        }
        if (this.groupDetail.getGroupComments() == null) {
            return 1;
        }
        if (this.groupDetail.getGroupComments().size() == 0) {
            return 1;
        }
        return 1 + this.groupDetail.getGroupComments().size();
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return VIEWTYPE_GROUP_DETAIL;
        } else {
            return VIEWTYPE_GROUP_COMMENTS;
        }
    }

    public static class MBDGroupDetailViewHolder extends RecyclerView.ViewHolder {
        private TextView nameTextView, textAuthorName, commentNumberTv;
        private TextView ageTextView;
        private ImageView groupLogo, ivCoe;


        public MBDGroupDetailViewHolder(@NonNull View itemView) {
            super(itemView);
            nameTextView = itemView.findViewById(R.id.text_group_name);
            textAuthorName = itemView.findViewById(R.id.text_author_name);
            ageTextView = itemView.findViewById(R.id.text_group_desc);
            groupLogo = itemView.findViewById(R.id.image_group_logo);
            ivCoe = itemView.findViewById(R.id.iv_coe);
            commentNumberTv = itemView.findViewById(R.id.comment_number_tv);

        }

        public void bind(MBDGroupDetailModel detail) {
            // 设置列表项视图的数据
            nameTextView.setText(detail.getGroupName());
            textAuthorName.setText((StringUtils.isNull(detail.getGroupPoster()) ? "" : detail.getGroupPoster()) + " " + detail.getCreateTime().substring(0, 10));
            ageTextView.setText(detail.getGroupDesc());
            if (null == detail.getGroupComments() || detail.getGroupComments().size() == 0) {
                commentNumberTv.setVisibility(View.GONE);
            } else {
                commentNumberTv.setVisibility(View.VISIBLE);
                commentNumberTv.setText("评论（" + detail.getGroupComments().size() + "）");
            }
            String imageUrl;
            if (detail.getGroupLogo().indexOf("http") > -1) {
                imageUrl = detail.getGroupLogo();
            } else {
                imageUrl = MBDHostManager.IMAGE_HOST + detail.getGroupLogo();
            }
            MBDImageUtils.imageDBL(imageUrl, groupLogo);
            if (!StringUtils.isNull(detail.praisedQrUrl)) {
                try {
                    generateQRCodeImage(detail.praisedQrUrl, 500, 500, Bitmap.Config.RGB_565, ivCoe);
                } catch (WriterException e) {
                    e.printStackTrace();
                }
            }
            ivCoe.setVisibility(!StringUtils.isNull(detail.praisedQrUrl) ? View.VISIBLE : View.GONE);
        }
    }

    private static void generateQRCodeImage(String text, int width, int height, Bitmap.Config config, ImageView imageView) throws WriterException {
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(
                text,
                BarcodeFormat.QR_CODE,
                width,
                height,
                hints
        );
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bitmap.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
            }
        }
        imageView.setImageBitmap(bitmap);
    }

    public static class MBDGroupCommentsViewHolder extends RecyclerView.ViewHolder {
        private TextView realNameTextView, timeTv;
        private TextView commentsTextView;
        private ImageView avatar, imageAvatarHide, likeIv;

        public MBDGroupCommentsViewHolder(@NonNull View itemView) {
            super(itemView);
            realNameTextView = itemView.findViewById(R.id.text_real_name);
            commentsTextView = itemView.findViewById(R.id.text_comments);
            avatar = itemView.findViewById(R.id.image_avatar);
            imageAvatarHide = itemView.findViewById(R.id.image_avatar_hide);
            timeTv = itemView.findViewById(R.id.time_tv);
            likeIv = itemView.findViewById(R.id.like_iv);
        }

        public void bind(MBDGroupCommentsModel comments, int position) {
            // 设置列表项视图的数据
            likeIv.setAlpha(!StringUtils.isNull(comments.isLike) && comments.isLike.equals("1") ? 1f : 0.5f);
            realNameTextView.setText(comments.realName);
            commentsTextView.setText(comments.comment);
            timeTv.setText(comments.createTime);
            imageAvatarHide.setVisibility(comments.flag == 1 ? View.GONE : View.VISIBLE);
            String imageUrl = MBDHostManager.IMAGE_HOST + comments.avatarUrl;
            int cornerRadius = 48; // 圆角半径，单位为像素
            RequestOptions options = new RequestOptions().transform(new CenterCrop(), new RoundedCorners(cornerRadius));
            Glide.with(MBDApplication.getContext()).load(imageUrl).placeholder(R.drawable.ico_appicon).error(R.drawable.ico_appicon).apply(options).into(avatar);
            itemView.findViewById(R.id.tv_comments).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    itemClickListener.onItemClick(comments, 1, position);
                }
            });
            itemView.findViewById(R.id.like_iv).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    itemClickListener.onItemClick(comments, 2, position);
                }
            });
        }
    }

    public static GroupDetailItemClickListener itemClickListener;

    public void setItemClickListener(GroupDetailItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public interface GroupDetailItemClickListener {
        void onItemClick(MBDGroupCommentsModel commentsModel, int type, int position);
    }
}
